/**
 * 
 */
package net.ddns.heroli.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.gzheroli.bfw.pojo.base.TSBaseUser;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.TreeGrid;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.HeroService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.manager.Client;
import cn.com.gzheroli.core.util.IdWorker;
import cn.com.gzheroli.core.util.NameHandler;
import cn.com.gzheroli.core.util.PasswordUtil;
import cn.com.gzheroli.core.util.RequestUtil;
import cn.com.gzheroli.core.util.oConvertUtils;
import cn.com.gzheroli.util.GenSqlUtil;
import net.ddns.heroli.pojo.TBBrand;
import net.ddns.heroli.pojo.TBRegion;
import net.ddns.heroli.pojo.TBShop;

/**  
* 类名: TenantController  
* 描述: 商户相关  
* 作者: 李长荣 lichang_20011@163.com  
* 日期: 2017年12月19日  下午3:54:41
*@version V1.0  
*    
*/
@Controller
@RequestMapping("/api/tenantUserController")
public class TenantUserController {
	private static final Logger logger = LoggerFactory.getLogger(ShopController.class);
	@Autowired
	private CommonService commonService;
	@Autowired
	private HeroService heroService;
	@Autowired
    private SpringRedisCache cache;
	@Autowired
	private SystemService systemService;
	@RequestMapping(value = "getCurrentShop")
	@ResponseBody
	public AjaxJson getCurrentShop( HttpServletRequest request) {		
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		Map para=new HashMap();
		para.put("id", user.getId());
		//TBShop shop=commonService.get(TBShop.class, id);
		String sql="select s.*,bu.REAL_NAME,bu.USER_NAME,u.* from T_B_SHOP s,T_S_BASE_USER bu,T_S_USER u ";
		sql=sql+" where s.ID=bu.ID and bu.ID=u.ID and bu.STATUS='1' and bu.ID=#id#";
		Map ret=heroService.findOneObjForJdbc(sql, para, Map.class);
		j.setObj(ret);
		j.setSuccess(true);
		j.setMsg("获取成功!");
		return j;
	}
	@RequestMapping(value = "areaList")
	@ResponseBody
	public  AjaxJson  areaList(HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		AjaxJson j = new AjaxJson();
		String page=request.getParameter("page")==null?"1":request.getParameter("page");
		String rows=request.getParameter("rows")==null?"1000":request.getParameter("rows");
		//Client client=cache.getCache(request.getSession().getId(), Client.class);
		Map reqMap=RequestUtil.convertParameterToMap(request);
		List<Map<String,Object>> treeGrids = new ArrayList<Map<String,Object>>();
		Map conMap=new HashMap();
		conMap.put("status", "=");
		if(!reqMap.containsKey("status"))
			reqMap.put("status", "1");
		if(reqMap.containsKey("parentId")) {
		conMap.put("parentId", "=");
		}else {
			conMap.put("parentId", "=");
			reqMap.put("parentId", "0");
		}
		if(reqMap.containsKey("name"))
		conMap.put("name", "like");
		Class clazz=TBRegion.class;
		String tableName = new NameHandler().getTableName(clazz.getSimpleName());
		Map<String,Object> tableColumns=systemService.getHeroTableColumns(tableName,clazz);
		String sql=GenSqlUtil.genSqlByClass(clazz, conMap,"list",tableColumns,"am",reqMap);
		List beanList =commonService.findForJdbcPage(sql, clazz, reqMap, Integer.parseInt(page), Integer.parseInt(rows));
		j.setObj(beanList);
		String countSql=GenSqlUtil.genSqlByClass(clazz, conMap,"count",tableColumns,"am",reqMap);
		Long total=commonService.getCountForJdbc(countSql, reqMap);
		j.setTotal(total);
		return j;
	}
	@RequestMapping(value = "get")
	@ResponseBody
	public AjaxJson get(String id, HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		if(id==null||id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("id不存在!");
			return j;
		}
		TSUser tenantUser=commonService.get(TSUser.class, id);
		j.setObj(tenantUser);
		j.setSuccess(true);
		j.setMsg("删除成功!");
		return j;
	}
	/**
	 * 
	* @Title del 
	* @Description 删除用户信息 
	* @param @param id
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "del")
	@ResponseBody
	public AjaxJson del(String id, HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		if(id==null||id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("id不存在!");
			return j;
		}
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		TSUser tenantUser=commonService.get(TSUser.class, id);
		tenantUser.setUpdateBy(user.getId());
		tenantUser.setUpdateTime(new Date());
		tenantUser.setUpdateByName(user.getRealName());
		tenantUser.setStatus(Short.valueOf("0"));
		commonService.update(tenantUser);
		j.setSuccess(true);
		j.setMsg("删除成功!");
		return j;
	}
	/**
	 * 
	* @Title update 
	* @Description 修改用户信息 
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "update")
	@ResponseBody
	public  AjaxJson update( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		String id=request.getParameter("id")==null?"":request.getParameter("id");
		TSUser user=client.getUser();
		if(id==null||id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("保存失败!,用户编号不能为空");
			return j;
		}else{
			Map reqMap=RequestUtil.convertParameterToMap(request);
			heroService.updateMap("T_S_BASE_USER", reqMap, null, TSBaseUser.class);
			reqMap.put("updateBy", user.getId());
			reqMap.put("updateTime", new Date());
			reqMap.put("updateByName", user.getRealName());
			heroService.updateMap("T_S_USER", reqMap, null, TSUser.class);
			
		}
		j.setSuccess(true);
		j.setMsg("保存成功!");
		return j;
	}
	/**
	 * 
	* @Title checkTenantUser 
	* @Description 审核用户信息
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "checkTenantUser")
	@ResponseBody
	public  AjaxJson checkTenantUser( HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		String id=request.getParameter("id")==null?"":request.getParameter("id");
		String state=request.getParameter("state")==null?"0":request.getParameter("state");//审核状态 0:未认证；1:已认证；2:已注销
		String checkMsg=request.getParameter("checkMsg")==null?"":request.getParameter("checkMsg");//审核信息
		TSUser user=client.getUser();
		if(id==null||id.trim().equals("")){
			j.setSuccess(false);
			j.setMsg("保存失败!,用户编号不能为空");
			return j;
		}else{
			Map reqMap=RequestUtil.convertParameterToMap(request);
			//reqMap.put("userType", value);
			reqMap.put("state", state);
			reqMap.put("id", id);
			if(state.equals("1")) {
				reqMap.put("checkMsg", "");
			}else {
				reqMap.put("checkMsg",checkMsg);
			}
			//heroService.updateMap("T_S_BASE_USER", reqMap, null, TSBaseUser.class);
			reqMap.put("updateBy", user.getId());
			reqMap.put("updateTime", new Date());
			reqMap.put("updateByName", user.getRealName());
			reqMap.put("checkUserId", user.getId());
			reqMap.put("checkTime", new Date());
			reqMap.put("checkUserName", user.getRealName());
			reqMap.put("departId", "1");
			heroService.updateMap("T_S_BASE_USER", reqMap, null, TSBaseUser.class);
			heroService.updateMap("T_S_USER", reqMap, null, TSUser.class);
			heroService.updateMap("T_B_SHOP", reqMap, null, TBShop.class);
		}
		j.setSuccess(true);
		j.setMsg("保存成功!");
		return j;
	}
	@RequestMapping(value = "save")
	@ResponseBody
	public  AjaxJson save(TSUser tenantUser, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		if(tenantUser.getId()==null){
			tenantUser.setUpdateBy(user.getId());
			tenantUser.setUpdateTime(new Date());
			tenantUser.setUpdateByName(user.getRealName());
			tenantUser.setStatus(Short.valueOf("1"));
			commonService.save(tenantUser);
		}else{
			tenantUser.setUpdateBy(user.getId());
			tenantUser.setUpdateTime(new Date());
			tenantUser.setUpdateByName(user.getRealName());
			commonService.update(tenantUser);
		}
		j.setSuccess(true);
		j.setMsg("保存成功!");
		return j;
	}
	/**
	 * 
	* @Title regUser 
	* @Description 用户注册
	* @param @param tenantUser
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "regUser")
	@ResponseBody
	public  AjaxJson regUser(TSUser tenantUser,TBShop shop, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		if(tenantUser==null||tenantUser.getUserName().trim().equals("")||tenantUser.getUserType().trim().equals("")){
			j.setSuccess(false);
			j.setMsg("请输入必要信息!");
			return j;
		}
		String userType=request.getParameter("userType")==null?"3":request.getParameter("userType");//用户类别 0:管理员 1:商家 2:卖家
		Map reqMap=RequestUtil.convertParameterToMap(request);
		List userList=heroService.findForSqlId("user.selectUser", reqMap);
		if(userList!=null&&!userList.isEmpty()) {
			j.setSuccess(false);
			j.setMsg("用户登录名重名!");
			return j;
		}
		String id=IdWorker.getFlowIdWorkerInstance().nextIdStr();
		if(userType.equals("1")) {
			shop.setUpdateTime(new Date());
			shop.setStatus("1");
			shop.setId(id);
			commonService.save(shop);
			tenantUser.setDepartId("3");
		} else if(userType.equals("2")) {
			tenantUser.setDepartId("2");
		}
		//tenantUser.setUpdateBy(user.getId());
		String password = oConvertUtils.getString(request.getParameter("password"));
		tenantUser.setPassword(PasswordUtil.encrypt(tenantUser.getUserName(),
				password, PasswordUtil.getStaticSalt()));
		tenantUser.setUpdateTime(new Date());
		//tenantUser.setUpdateByName(user.getRealName());
		tenantUser.setStatus(Short.valueOf("1"));
		tenantUser.setId(id);
		commonService.save(tenantUser);
		j.setSuccess(true);
		j.setMsg("保存成功!");
		return j;
	}
	@RequestMapping(value = "list")
	@ResponseBody
	public  AjaxJson  list(HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
		AjaxJson j = new AjaxJson();
		String page=request.getParameter("page")==null?"1":request.getParameter("page");
		String rows=request.getParameter("rows")==null?"1000":request.getParameter("rows");
		//Client client=cache.getCache(request.getSession().getId(), Client.class);
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			//return null;
		}else{
			TSUser user=client.getUser();
		}
		Map reqMap=RequestUtil.convertParameterToMap(request);
		List<Map<String,Object>> treeGrids = new ArrayList<Map<String,Object>>();
		Map conMap=new HashMap();
		conMap.put("status", "=");
		if(!reqMap.containsKey("status"))
			reqMap.put("status", "1");
		if(reqMap.containsKey("proId"))
		conMap.put("proId", "=");
		if(reqMap.containsKey("name"))
		conMap.put("name", "like");
		if(reqMap.containsKey("code"))
			conMap.put("code", "like");
		Class clazz=TSUser.class;
		String tableName = new NameHandler().getTableName(clazz.getSimpleName());
		Map<String,Object> tableColumns=systemService.getHeroTableColumns(tableName,clazz);
		String sql=GenSqlUtil.genSqlByClass(clazz, conMap,"list",tableColumns,"am",reqMap);
		List beanList =commonService.findForJdbcPage(sql+" and USER_NAME!='admin'", clazz, reqMap, Integer.parseInt(page), Integer.parseInt(rows));
		j.setObj(beanList);
		String countSql=GenSqlUtil.genSqlByClass(clazz, conMap,"count",tableColumns,"am",reqMap);
		Long total=commonService.getCountForJdbc(countSql+" and USER_NAME!='admin'", reqMap);
		j.setTotal(total);
		return j;
	}
}
